import React, { HtmlHTMLAttributes, useEffect, useRef, useState } from 'react';
import { View, Text, StyleSheet, Animated, Dimensions } from 'react-native';
import Feather from 'react-native-vector-icons/Feather';

interface INoticeBarProps {
  content: string;
  iconName: string;
  isScroll: boolean;
}

const NoticeBar: React.FC<INoticeBarProps> = ({ content, iconName, isScroll }) => {
  const animatedValue = new Animated.Value(0);
  const [textWidth, setTextWidth] = useState(0);
  const [readWidth, setReadWidth] = useState(0);

  const [translateX, setTranslateX] = useState(
    animatedValue.interpolate({
      inputRange: [0, 1],
      outputRange: [0, -0],
    }),
  );
  //设置动画播放
  const playOptions = {
    toValue: 1, // 动画的终点
    duration: 10000, // 动画的持续时间
    useNativeDriver: isScroll,
  };
  const startAnimation = () => {
    animatedValue.setValue(0); // 重置动画值
    Animated.timing(animatedValue, playOptions).start(() => startAnimation()); // 动画完成后重新开始
  };
  const viewLayout = (event: any) => {
    let { x, y, width, height } = event.nativeEvent.layout;
    const textLength = content.length * 15;
    if (textLength > width) {
      setTextWidth(textLength);
    } else {
      setTextWidth(width);
    }
  };
  useEffect(() => {
    if (textWidth > 0) {
      setTranslateX(
        animatedValue.interpolate({
          inputRange: [0, 1],
          outputRange: [textWidth, -textWidth],
        }),
      ); // 从右到左滚动
      if (isScroll) {
        startAnimation();
      }
    }
  }, [textWidth]);

  return (
    <>
      <View style={styles.tips}>
        <View style={{ width: '10%' }}>
          <Feather name={iconName} size={24} color="#ff7b30"></Feather>
        </View>
        <View
          onLayout={(e) => {
            viewLayout(e);
          }}
          style={{ width: '90%', overflow: 'hidden', flexWrap: 'nowrap' }}
        >
          <Animated.View style={{ transform: isScroll ? [{ translateX }] : undefined }}>
            {isScroll ? (
              <Text style={[styles.text, { width: textWidth }]}>{content}</Text>
            ) : (
              <Text numberOfLines={1} ellipsizeMode={'tail'} style={[styles.text]}>
                {content}
              </Text>
            )}
          </Animated.View>
        </View>
      </View>
    </>
  );
};

const styles = StyleSheet.create({
  text: {
    fontSize: 14,
    fontWeight: 'bold',
    color: '#ff7b30',
  },
  tips: {
    width: '100%',
    flexDirection: 'row',
    alignItems: 'center',
    height: 50,
    padding: 10,
    borderRadius: 8,
    backgroundColor: '#fff9ed',
    overflow: 'hidden',
  },
});

export default NoticeBar;
